package com.adouteam.simple.wechat.service;

import com.adouteam.simple.wechat.base.WechatConstants;
import com.adouteam.simple.wechat.base.WeixinUrls;
import com.adouteam.simple.wechat.bean.template.TemplateResult;
import com.adouteam.simple.wechat.template.DataOfTemplate;
import com.adouteam.simple.wechat.template.Template;
import com.adouteam.simple.wechat.tool.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.Map;

public class TemplateService {
    private static final Logger logger = LoggerFactory.getLogger(TemplateService.class);

    protected TemplateService() {
    }

    private static TemplateService ME = new TemplateService();

    public static TemplateService getInstance() {
        return ME;
    }

    public static Template buildTemplate(String template_id, String url, String toUser, Map<String, DataOfTemplate> dataOfTemplateMap) {
        Template template = new Template();
        template.setTemplate_id(template_id);
        template.setUrl(url);
        template.setTouser(toUser);
        template.setDataOfTemplateMap(dataOfTemplateMap);
        return template;
    }

    public static TemplateResult sendTemplateToUser(Template template, WechatConstants wechatConstants) {
        if (template == null) {
            return null;
        }
        System.out.println(template.toJson());
        String url = WeixinUrls.replace(WeixinUrls.TEMPLATE_URL, wechatConstants, null);
        String jsonData = template.toJson();
        HttpEntity httpEntity = EntityBuilder.create()
                .setText(jsonData)
                .setContentEncoding(Consts.UTF_8.name())
                .setContentType(ContentType.APPLICATION_JSON)
                .build();
        return HttpUtil.post(url, null, httpEntity, httpResponse -> {
            String responseContent = EntityUtils.toString(httpResponse.getEntity(), Charset.forName("utf-8"));
            System.out.println("====responseContent=====" + responseContent);
            return JSONObject.parseObject(responseContent, TemplateResult.class);
        });
    }
}
